package com.hitcoder.chat.emoji

import android.content.Context
import android.text.Spannable
import android.text.SpannableString
import androidx.core.content.ContextCompat
import com.hitcoder.chat.emoji.Emotions.getDrawableResByName
import com.hitcoder.chat.utils.dip2px
import java.util.regex.Pattern

/**
 * Created by yummyLau on 18-7-11
 * Email: yummyl.lau@gmail.com
 * blog: yummylau.com
 */
object EmojiSpanBuilder {
    private val sPatternEmotion =
        Pattern.compile("\\[([\u4e00-\u9fa5\\w])+\\]|[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]")

    fun buildEmotionSpannable(context: Context, text: String): Spannable {
        val spannableString = SpannableString(text)
        val matcherEmotion = sPatternEmotion.matcher(text)
        while (matcherEmotion.find()) {
            val key = matcherEmotion.group()
            val imgRes = getDrawableResByName(key)
            if (imgRes != -1) {
                val start = matcherEmotion.start()
                val drawable = ContextCompat.getDrawable(context, imgRes)
                drawable?.setBounds(0, 0, 20f.dip2px(context), 20f.dip2px(context))
                val span = CenterImageSpan(drawable)
                spannableString.setSpan(
                    span,
                    start,
                    start + key.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        return spannableString
    }
}